<?php

namespace WeForge;

use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Queue;
use WeForge\Queue\Connectors\FnfConnector;

trait ExtendsQueues
{
    /**
     * Queue extensions.
     *
     * @return void
     */
    protected function extendQueues()
    {
        $this->extendFnfQueue();
        // $this->extendFcQueue();
        // $this->extendMnsQueue();
    }

    /**
     * Fc extension.
     *
     * @return void
     */
    protected function extendFcQueue()
    {
        $extender = function () {
            Queue::extend('fc', function () {
                return new FcConnector;
            });
        };

        $this->app->resolved('queue')
                        ? call_user_func($extender)
                        : $this->app->afterResolving('queue', $extender);

        Config::set('queue.connections.fc', [
            'driver' => 'fc',
            'key' => $_ENV['accessKeyID'] ?? $_ENV['ALIYUN_ACCESS_KEY_ID'] ?? null,
            'secret' => $_ENV['accessKeySecret'] ?? $_ENV['ALIYUN_SECRET_ACCESS_KEY'] ?? null,
            'security_token' => $_ENV['securityToken'] ?? $_ENV['ALIYUN_ACCESS_SECURITY_TOKEN'] ?? null,
            'endpoint' => $_ENV['WEFORGE_FC_ENDPOINT'] ?? null,
        ]);
    }

    protected function extendFnfQueue()
    {
        $extender = function () {
            Queue::extend('fnf', function () {
                return new FnfConnector;
            });
        };

        $this->app->resolved('queue')
                        ? call_user_func($extender)
                        : $this->app->afterResolving('queue', $extender);

        Config::set('queue.connections.fnf', [
            'driver' => 'fnf',
            'key' => $_ENV['accessKeyID'] ?? $_ENV['ALIYUN_ACCESS_KEY_ID'] ?? null,
            'secret' => $_ENV['accessKeySecret'] ?? $_ENV['ALIYUN_SECRET_ACCESS_KEY'] ?? null,
            'security_token' => $_ENV['securityToken'] ?? $_ENV['ALIYUN_ACCESS_SECURITY_TOKEN'] ?? null,
            'endpoint' => $_ENV['FNF_ENDPOINT'] ?? null,
            'flow' => $_ENV['FNF_FLOW'] ?? null,
        ]);
    }

    protected function extendMnsQueue()
    {
        $extender = function () {
            Queue::extend('mns', function () {
                return new MnsConnector;
            });
        };

        $this->app->resolved('queue')
                        ? call_user_func($extender)
                        : $this->app->afterResolving('queue', $extender);

        Config::set('queue.connections.mns', [
            'driver' => 'mns',
            'key' => $_ENV['accessKeyID'] ?? $_ENV['ALIYUN_ACCESS_KEY_ID'] ?? null,
            'secret' => $_ENV['accessKeySecret'] ?? $_ENV['ALIYUN_SECRET_ACCESS_KEY'] ?? null,
            'security_token' => $_ENV['securityToken'] ?? $_ENV['ALIYUN_ACCESS_SECURITY_TOKEN'] ?? null,
            'endpoint' => $_ENV['MNS_ENDPOINT'] ?? null,
            'queue' => $_ENV['MNS_QUEUE'] ?? null,
        ]);
    }
}
